package com.reebake.ideal.message.mail.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.reebake.ideal.message.mail.entity.MailAttachmentEntity;
import com.reebake.ideal.message.mail.service.MailSendService;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MailSendServiceImpl implements MailSendService {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private MailProperties mailProperties;
    @Override
    public void sendMail(String subject, String content, List<MailAttachmentEntity> attachments, String to) throws MessagingException {
        String from = mailProperties.getUsername();
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // 是否有附件资源
        boolean multipart = CollectionUtil.isNotEmpty(attachments);
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, multipart);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        //默认发送html格式
        helper.setText(content, true);

        //添加附件
        if(CollectionUtil.isNotEmpty(attachments)) {
            for (MailAttachmentEntity attachment : attachments) {
                helper.addAttachment(attachment.getName(), attachment.getFile());
            }
        }

        javaMailSender.send(mimeMessage);
    }
}
